package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {


    public static final String wx_login = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;


    // 调用service 向微信发送http请求 拿到openid；同时 如果是新用户 插入数据库 ；返回user对象
    public User wxlogin(UserLoginDTO userLoginDTO) {


        // 1. 调用微信服务 得到每一个用户 唯一的 openid
        HashMap<String, String> mp = new HashMap<>();
        mp.put("appid",weChatProperties.getAppid());
        mp.put("secret",weChatProperties.getSecret());
        mp.put("js_code",userLoginDTO.getCode());
        mp.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(wx_login, mp);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        // 2. 判断openid是否为空
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 3. openid不为空 根据openid判断用户是否是新用户

        User user = userMapper.getByOpenid(openid);
        // 4. 新用户 插入数据库user表
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        // 5. 返回这个user对象

        return user;
    }


}
